<template>
    <div class="mainBox">
        <div class="actionBox">
            <div class="addBtn" @click="adduser">新增</div>
        </div>
        <div class="tabBox">
            <el-table :data="tableData" border :row-class-name="tableRowClassName">
                <el-table-column prop="username" align="center" label="用户名" width="150"></el-table-column>
                <el-table-column prop="phone" align="center" label="电话" width="300"></el-table-column>
                <el-table-column prop="organization" align="center" label="所属组织" width="200"></el-table-column>
                <el-table-column align="center" label="角色" width="300">
                   <template slot-scope="scope">
                        <div>
                            {{scope.row.roleList.map(item=>item.roleName).join('、')}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" align="center" label="备注"></el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <div class="actionTr">
                            <span class="editText" @click="editFunc(scope.row)">修改</span>
                            <!-- {{scope.row.roleList[0].roleName}} -->
                            <span class="delText" v-if="scope.row.roleList.map(item=>item.roleName).indexOf('root') ==-1 && scope.row.userId != userid" @click="delFunc(scope.row)"
                                >删除</span
                            >
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                background
                layout=" prev, pager, next"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="pageTotal"
                @current-change="handlePageChange"
            ></el-pagination>
        </div>
        <!-- 新增弹框 -->
        <div class="specity1">
            <el-dialog :title="title" :visible.sync="addPop" width="590px" @close="decomposeCancle" class="specityBox">
                <div class="tableBox">
                    <el-form
                        :model="ruleForm"
                        :rules="rules"
                        ref="ruleForm"
                        :show-message="true"
                        class="newForm"
                        :validate-on-rule-change="false"
                    >
                        <el-form-item prop="username">
                            <el-input
                                type="text"
                                class="newFormInput"
                                v-model="ruleForm.username"
                                onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
                                maxlength="13"
                                placeholder="请输入用户名"
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="phone">
                            <el-input
                                class="newFormInput"
                                v-model.number="ruleForm.phone"
                                oninput="value=value.replace(/[^\d]/g,'')"
                                maxlength="11"
                                placeholder="请输入电话"
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="remark">
                            <el-input class="newFormInput" v-model="ruleForm.remark" maxlength="50" placeholder="请输入备注"></el-input>
                        </el-form-item>
                        <el-form-item prop="deptid">
                            <el-select class="newFormInput newFormSelect" v-model="ruleForm.deptid" placeholder="请选择部门">
                                <el-option
                                    :label="item.organizationName"
                                    :value="item.id"
                                    v-for="(item, index) in departmentlist"
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="roleIds" ref="roleIds">
                            <template>
                                <img src="@/assets/img/icon_search_moren.png" class="selimg" />
                            </template>
                            <el-select
                                class="newFormInput newFormSelect postsel"
                                v-model="mineStatus"
                                placeholder="请选择职位"
                                :multiple="true"
                                @change="selectChange"
                            >
                                <el-option :value="mineStatusValue" style="height: auto">
                                    <el-tree
                                        :data="data"
                                        show-checkbox
                                        node-key="id"
                                        ref="tree"
                                        highlight-current
                                        check-strictly="true"
                                        :props="defaultProps"
                                        :default-checked-keys="ruleForm.roleIds"
                                        @check-change="handleCheckChange"
                                    ></el-tree>
                                </el-option>
                            </el-select>
                            <!-- {{ruleForm.roleIds}} -->
                            <!-- <el-select class="newFormInput newFormSelect" multiple v-model="ruleForm.roleIds" placeholder="请选择职位">
                                <el-option :label="item.roleName" :value="item.id" v-for="item in RoleList" :key="item.id"></el-option>
                            </el-select> -->
                        </el-form-item>
                    </el-form>
                </div>
                <div class="tableBtnBox">
                    <button class="btn2" @click="decomposeConfirm">确认</button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { userlist, commongetOrganizationList, commongetRoleList, useradd, userdelete, userupdate, roleList } from '@/api/index';
export default {
    data() {
        return {
            tableData: [], //用户列表数据
            currentPage: 1,
            pageSize: 10,
            pageTotal: 1,
            addPop: false, //新增弹窗状态
            title: '', //新增、修改弹窗标题
            mineStatus: '',
            mineStatusValue: [],
            data: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            ruleForm: {
                username: '',
                phone: '',
                remark: '',
                deptid: '',
                roleIds: ''
            }, //新增用户表单数据
            rules: {
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { type: 'number', message: '电话必须为数字', trigger: 'blur' }
                ],
                remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
                deptid: [{ required: true, message: '请选择部门', trigger: 'change' }]
                // roleIds: [{ required: true, message: '请选择职位', trigger: 'change' }]
            },
            departmentlist: [], //部门列表
            RoleList: [], //职位列表
            userid: '' //用户id
        };
    },
    watch: {
        // eslint-disable-next-line no-unused-vars
        isShowSelect(val) {
            // 隐藏select自带的下拉框
            this.$refs.select.blur();
        }
        // treeData(){//监听tree数据
        //   this.$nextTick(()=> {
        //            this.init();
        //           })
        // }
    },
    mounted() {
        this.userid = localStorage.getItem('userid');
        // 获取列表数据
        this.getlist();
        // 获取部门列表
        this.getDepartmentList();
        this.getrolelist();
    },
    methods: {
        // 获取角色列表
        getrolelist() {
            roleList().then(res => {
                if (res.code == 200) {
                    this.data = res.result;
                }
            });
            
        },
        // 获取用户列表数据
        getlist() {
            userlist({
                page: this.currentPage,
                size: this.pageSize
            }).then(res => {
                if (res.code == 200) {
                    this.tableData = res.result.userList || [];
                    this.tableData.forEach(item => {
                        if (item.roleList[0] && item.roleList[0].roleName == 'root') {
                            item.role = item.roleList[0].roleName;
                        }
                    });
                    this.pageTotal = res.result.pageInfo.total;
                    this.currentPage = res.result.pageInfo.current;
                    // this.pageSize = res.result.pageInfo.size;
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        getlist2() {
            userlist({
                page: this.currentPage,
                size: this.pageSize
            }).then(res => {
                if (res.code == 200) {
                    this.tableData = res.result.userList || [];
                    this.tableData.forEach(item => {
                        if (item.roleList[0] && item.roleList[0].roleName == 'root') {
                            item.role = item.roleList[0].roleName;
                        }
                    });
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        tableRowClassName({ row, rowIndex }) {
            if (rowIndex === 1) {
                return 'warning-row';
            } else if (rowIndex === 3) {
                return 'success-row';
            }
            return '';
        },
        // 分页导航
        handlePageChange(val) {
            this.currentPage = val;
            userlist({
                page: this.currentPage
            }).then(res => {
                if (res.code == 200) {
                    this.tableData = res.result.userList || [];
                }
            });
        },
        // 删除用户
        delFunc(item) {
            this.$confirm(`是否删除【${item.username}】？`, {
                customClass: 'newObjectConfirm',
                center: true,
                showClose: false,
                cancelButtonClass: 'newObjectCancel',
                confirmButtonClass: 'newObjectConfirm'
            })
                .then(res => {
                    if (item.userId == localStorage.getItem('userid')) {
                        this.$message.success('无法删除当前用户');
                        return;
                    }
                    if (item.role == 'root') {
                        this.$message.success('无法root用户');
                        return;
                    }
                    userdelete({ userId: item.userId }).then(res => {
                        if (res.code == 200) {
                            this.$message.success('删除成功');
                            console.log(this.tableData);
                            if (this.tableData.length == 1) {
                                this.currentPage = this.currentPage - 1;
                            } else {
                                this.currentPage = this.currentPage;
                            }

                            this.getlist();
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                })
                .catch(() => {});
        },
        // 点击编辑
        editFunc(data) {
            this.title = '修改用户';
            this.ruleForm = {
                username: '',
                phone: '',
                remark: '',
                deptid: '',
                roleIds: []
            };
            this.mineStatus = [];
            this.ruleForm.username = data.username;
            this.ruleForm.userId = data.userId;
            this.ruleForm.phone = data.phone;
            this.ruleForm.remark = data.remark;
            this.ruleForm.deptid = data.organizationId || '';

            if (data.roleList.length) {
                data.roleList.forEach(item => {
                    this.mineStatusValue.push(item);
                    this.ruleForm.roleIds.push(item.id);
                    this.mineStatus.push(item.roleName);
                });
            } else this.ruleForm.roleIds = [];
            this.addPop = true;
            if (this.data.length == 0) {
                this.getrolelist();
            }
            // this.$refs.tree.setCheckedNodes(this.ruleForm.roleIds);
        },
        // 关闭弹窗
        decomposeCancle() {
            // this.$refs['ruleForm'].resetFields();
            this.$nextTick(() => {
                this.$refs['ruleForm'].resetFields();
            });
            this.ruleForm = {
                username: '',
                phone: '',
                remark: '',
                deptid: '',
                roleIds: []
            };
            this.addPop = false;
            this.data = [];
            this.getrolelist();
        },
        // 确认新增/修改
        decomposeConfirm() {
            //项目名称
            if (!this.ruleForm.username) {
                this.$message.error('用户名不能为空');
                return;
            }
            if (!this.ruleForm.phone) {
                this.$message.error('电话不能为空');
                return;
            }
            if (!this.ruleForm.remark) {
                this.$message.error('备注不能为空');
                return;
            }
            if (!this.ruleForm.deptid) {
                this.$message.error('部门不能为空');
                return;
            }
            if (!this.ruleForm.roleIds) {
                this.$message.error('职位不能为空');
                return;
            } else {
                // this.ruleForm.roleIds = this.unique(this.ruleForm.roleIds);
            }
            // console.log(this.ruleForm)
            if (this.ruleForm.userId) {
                userupdate(this.ruleForm).then(res => {
                    if (res.code == 200) {
                        this.$message.success('修改成功');
                        // this.addPop = false;
                        this.decomposeCancle();
                        this.getlist2();
                    } else {
                        this.$message.success(res.message);
                    }
                });
            } else {
                useradd(this.ruleForm).then(res => {
                    if (res.code == 200) {
                        this.$message.success('新增成功');
                        this.decomposeCancle();
                        this.getlist();
                    } else {
                        this.$message.success(res.message);
                    }
                });
            }
        },
        // 获取部门列表
        getDepartmentList() {
            commongetOrganizationList().then(res => {
                if (res.code == 200) {
                    this.departmentlist = res.result || [];
                }
            });
        },
        
        // 点击新增用户
        adduser() {
            this.title = '新增用户';
            this.addPop = true;
            // this.$nextTick(() => {
            //     this.$refs['ruleForm'].resetFields();
            // });
            this.ruleForm = {
                username: '',
                phone: '',
                remark: '',
                deptid: '',
                roleIds: []
            };
            this.ruleForm.deptid = '';
            this.mineStatus = [];
            if (this.data.length == 0) {
                this.getrolelist();
            }
            this.$refs.tree.setCheckedNodes([]);
            console.log(this.ruleForm)
        },
        //select框值改变时候触发的事件
        selectChange(e) {
          // this.ruleForm.roleIds = []
            var arrNew = [];
            var data =[];
            var dataLength = this.mineStatusValue.length;
            var eleng = e.length;
            for (let i = 0; i < dataLength; i++) {
                for (let j = 0; j < eleng; j++) {
                    if (e[j] === this.mineStatusValue[i].label) {
                        arrNew.push(this.mineStatusValue[i]);
                    }
                    if (e[j] === this.mineStatusValue[i].id) {
                       data.push(this.mineStatusValue[i].id);
                    }
                }
            }
            this.ruleForm.roleIds = data;
            // this.ruleForm.roleIds = this.unique(this.ruleForm.roleIds)
            this.$refs.tree.setCheckedNodes(arrNew); //设置勾选的值
            console.log(this.ruleForm.roleIds)
            
        },
        handleCheckChange() {
            let res = this.$refs.tree.getCheckedNodes(false,true); //这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
          //  console.log(this.$refs.tree)
            let arrLabel = [];
            this.ruleForm.roleIds = []
            let arr = [];
            res.forEach(item => {
                arrLabel.push(item.label);
                this.ruleForm.roleIds.push(item.id);
                arr.push(item);
            });
            this.mineStatusValue = arr.map(item => {
                return item;
            });
            this.mineStatus = arrLabel;
            console.log(this.ruleForm)
            // if (this.mineStatus) {
            //     this.mineStatus = [...this.mineStatus, ...arrLabel];
            // } else this.mineStatus = arrLabel;
            // this.mineStatus=this.unique(this.mineStatus)
        },
        unique(arr) {
            const res = new Map();
            return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
        }
    }
};
</script>

<style lang="scss" scope>
.mainBox {
    width: 100%;
    height: 100%;
    background: #ffffff;
    border-radius: 0.3125rem /* 5/16 */;
    box-shadow: 0px 11px 14px -10px #e5eced;
    padding: 1.625rem /* 26/16 */ 1.875rem /* 30/16 */ 3.125rem /* 50/16 */ 1.875rem /* 30/16 */;
    box-sizing: border-box;
    .actionBox {
        text-align: left;
        margin-bottom: 1.25rem /* 20/16 */;
        .addBtn {
            width: 5.125rem /* 82/16 */;
            height: 2.1875rem /* 35/16 */;
            background: #214a8f;
            border-radius: 0.3125rem /* 5/16 */;
            color: #fff;
            font-size: 1rem /* 16/16 */;
            text-align: center;
            line-height: 2.1875rem /* 35/16 */;
            cursor: pointer;
        }
    }
    .tabBox {
        height: 80%;
        .el-table .warning-row {
            background: oldlace;
        }
        .el-table .success-row {
            background: #f0f9eb;
        }
        .actionTr {
            padding: 0 35%;
            display: flex;
            justify-content: center;
            > span {
                text-decoration: underline;
                cursor: pointer;
            }
            .editText {
                color: #0091ff;
            }
            .delText {
                margin-left: 1.25rem /* 20/16 */;
                color: #eb194a;
            }
        }
        .actionTrOne {
            justify-content: center;
        }
    }
    .specityBox {
        .tableBox {
            // border:1px solid red;
            max-height: 452px;
            overflow-y: scroll;
        }
        .tableBox::-webkit-scrollbar {
            width: 0;
        }
    }
    .tableBtnBox {
        margin-top: 64px;
        // margin-bottom:64px!important;
        text-align: center;
        .btn1 {
            width: 90px;
            height: 35px;
            background: rgba(0, 79, 171, 0.2);
            border-radius: 5px;
            border: none;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 79, 171, 1);
            margin-right: 56px;
        }
        .btn2 {
            width: 90px;
            height: 35px;
            background: rgba(0, 79, 171, 1);
            border-radius: 5px;
            border: none;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
        }
    }
    .newForm {
        // .el-form-item {
        //     border-bottom: 1px solid #d8d8d8;
        //     margin-bottom: 0;
        // }
        // .el-form-item__error {
        //     z-index: 1;
        // }

        .newFormInput /deep/.el-input__inner {
            // border: none;
            // width: 100%;
            // height: 62px;
            // line-height: 62px;
            width: 19.625rem /* 314/16 */;
        }
        // /deep/ .el-select {
        //     width: 100%;
        // }
        // /deep/.el-form-item__label {
        //     font-size: 16px;
        //     padding: 0;
        //     line-height: 62px;
        // }
        // .duoxuan {
        //     /deep/.selected {
        //         color: #eb194a !important;
        //     }
        // }
    }
}
.el-popover {
    /deep/.el-checkbox-group {
        display: flex;
        flex-direction: column;
        width: 100%;
    }
}
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
    background: none;
}
.selimg {
    position: absolute;
    top: 8px;
    left: 10px;
    z-index: 9999;
    width: 16px;
}
.mainBox .newForm .postsel /deep/ .el-input__inner {
    padding-left: 34px;
}
.el-select__tags{
  padding-left: 24px;
}
#app/deep/.el-icon-close:before {
    border-radius: none;
    // color: #fff;
    background-color:none;
    // font-size: 14px;
    padding: 0;
    width:0;
    height:0;
}
</style>
